package com.dave.gd.common.util.serial;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
 * 序列化工具类
 * 
 * @author kenny
 *
 */
public class HessianSerializeUtils {
    
    /**
     * Hessian 序列化
     * 
     * @param obj
     * @return
     * @throws IOException
     */
    public static byte[] serializeHessian(Object obj) throws IOException {
        if (obj == null)
            throw new NullPointerException();
        ByteArrayOutputStream os = null;
        HessianOutput ho = null;
        byte[] bytes = null;
        try {
            os = new ByteArrayOutputStream();
            ho = new HessianOutput(os);
            ho.writeObject(obj);
            bytes = os.toByteArray();
        } catch (Exception e) {
            e.fillInStackTrace();
        } finally {
            if (os != null) {
                os.close();
            }
            if (ho != null) {
                ho.close();
            }
        }
        return bytes;
    }
    
    /**
     * Hessian 反序列化
     * 
     * @param by
     * @return
     * @throws IOException
     */
    public static Object deserializeHessian(byte[] by) throws IOException {
        Object obj = null;
        if (by == null)
            return obj;
        HessianInput hi = null;
        ByteArrayInputStream is = null;
        try {
            is = new ByteArrayInputStream(by);
            hi = new HessianInput(is);
            obj = hi.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                is.close();
            }
            if (hi != null) {
                hi.close();
            }
        }
        return obj;
    }
}
